<template>
  <el-dialog
    v-model="visible"
    title="关联房间"
    width="700px"
    :destroy-on-close="true"
  >
    <div class="header-search">
      <el-input
        v-model="queryParams.roomName"
        placeholder="输入房间名称搜索"
        clearable
        style="width: 300px"
        @keyup.enter="handleQuery"
      >
        <template #append>
          <el-button :icon="Search" @click="handleQuery" />
        </template>
      </el-input>
    </div>
    
    <el-table
      v-loading="loading"
      :data="displayRoomList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="name" label="房间名称" />
      <el-table-column prop="buildingName" label="所属楼栋" />
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="bindRoom(scope.row)">绑定</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="selectedRooms.length === 0"
          @click="batchBind"
        >批量绑定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="AssociateRoomDialog">
import { ref, computed, watch, getCurrentInstance } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { getUnboundRooms, batchBindRoom } from '@/api/device/faceLock.js'

const { proxy } = getCurrentInstance()

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  faceLockId: {
    type: [Number, String],
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  }
})

const loading = ref(false)
const roomList = ref([])
const filteredRoomList = ref([])
const selectedRooms = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const queryParams = ref({
  roomName: ''
})

// 计算过滤后的总数
const filteredTotal = computed(() => {
  return filteredRoomList.value.length
})

// 计算当前页显示的数据
const displayRoomList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRoomList.value.slice(start, end)
})

// 监听对话框打开，加载未关联房间列表
watch(() => visible.value, (val) => {
  if (val && props.faceLockId) {
    loadUnboundRoomList()
  }
})

// 加载未绑定房间列表
function loadUnboundRoomList() {
  if (!props.faceLockId) return
  
  loading.value = true
  getUnboundRooms(props.faceLockId, queryParams.value).then(res => {
    roomList.value = res.data || []
    filterRoomList()
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 过滤房间列表
function filterRoomList() {
  if (!queryParams.value.roomName) {
    filteredRoomList.value = [...roomList.value]
    return
  }
  
  filteredRoomList.value = roomList.value.filter(room => 
    room.name && room.name.toLowerCase().includes(queryParams.value.roomName.toLowerCase())
  )
  
  // 重置为第一页
  currentPage.value = 1
}

// 表格选择变化
function handleSelectionChange(selection) {
  selectedRooms.value = selection
}

// 搜索
function handleQuery() {
  // API 不支持分页，在前端实现搜索过滤
  filterRoomList()
}

// 每页数量变化
function handleSizeChange(size) {
  pageSize.value = size
}

// 页码变化
function handleCurrentChange(page) {
  currentPage.value = page
}

// 绑定单个房间
function bindRoom(row) {
  const roomIds = row.roomId
  
  batchBindRoom(props.faceLockId, roomIds).then(() => {
    proxy.$modal.msgSuccess('绑定成功')
    loadUnboundRoomList()
    emit('success')
  })
}

// 批量绑定房间
function batchBind() {
  if (selectedRooms.value.length === 0) return
  
  const roomIds = selectedRooms.value.map(item => item.roomId).join(',')
  
  batchBindRoom(props.faceLockId, roomIds).then(() => {
    proxy.$modal.msgSuccess('批量绑定成功')
    loadUnboundRoomList()
    emit('success')
  })
}

// 添加visible值变化的监听，当对话框关闭时触发刷新
watch(() => visible.value, (val, oldVal) => {
  // 当对话框从显示变为隐藏状态
  if (oldVal === true && val === false) {
    // 通知父组件可能需要刷新
    emit('success')
  }
})
</script>

<style scoped>
.header-search {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}
</style> 